/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedBean.TX.OutletManagement;

import session.TX.PhotoUploadSB;
import managedBean.TX.CustomerIOTRPortal.FakeMainPortalMB;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.primefaces.event.FileUploadEvent;

/**
 *
 * @author Shawn Chia
 */
@ManagedBean(name = "photoManagedBean")
@SessionScoped
public class PhotoMB {

    //inject session bean
    @EJB
    PhotoUploadSB portalManagementSB;

    /////////////////////////////////////////////////////////////////////////////
    //FakeMainPortalMB a = getPortalManagedBean();
    //String  uploaderName ; //
    //String stakeholderName="ssa"; //
    /////////////////////////////////////////////////////////////////////////////
    private static final int BUFFER_SIZE = 6124;
    //used for upload
    private String folderToUpload;
    private String photoURLToShow;
    //to be used for manage photo form
    private ArrayList<String> photoIDCollection;
    private List<String> images;
    //galleria effect
    private String effect = "fade";
    //
    private String altDesc;
    private String singlePhotoStr;
    private String photoFilePath;

    /** Creates a new instance of UploadBean */
    public PhotoMB() {
    }

    //populates selection form field //change type if for others.
   /* @PostConstruct
    public void init() {
    ////////////////////////////////////////////////////////////////////////
    images = portalManagementSB.getAllPhotoToString(getPortalManagedBean().getOutletId().toString(), "gallery");
    ////////////////////////////////////////////////////////////////////////
    }
     */
    public void populateAlt() {
        try {
            String photoID = photoIDCollection.get(0); //form support multiple selection get single just get first photo. 
            altDesc = portalManagementSB.getPhotoAlt(Long.parseLong(photoID));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addAlt() {
        try {
            String photoID = photoIDCollection.get(0); //form support multiple selection get single just get first photo. 
            portalManagementSB.addAlt(Long.parseLong(photoID), altDesc);

            FacesMessage msg = new FacesMessage("Sucessful", "Alt Added.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //split the images to file and alts.
    public String splitString(String a, Integer type) {
        if (a.contains(",")) {
            String[] temp = a.split(",");
            if (type == 0) {
                return temp[0];
            }
            if (type == 1) {
                return temp[1];
            }
        }
        return a;
    }

    //for viewing of photo in manage picture
    public void getSinglePhoto() {
        String photoID = "";
        try {
            System.out.println(photoIDCollection.get(0));
            photoID = photoIDCollection.get(0); //form support multiple selection get single just get first photo.    
        } catch (Exception e) {
            e.printStackTrace();
        }
        photoURLToShow = portalManagementSB.getSinglePhotoUrl(Long.parseLong(photoID));
    }

    //allows multiple delete
    public void deletePhoto() {
        photoURLToShow = null; //sets photoURLToShow to null so picture deleted wont be cache in this managed bean.
        for (int i = 0; i < photoIDCollection.size(); i++) {
            portalManagementSB.deletePhoto(Long.parseLong(photoIDCollection.get(i)));
        }

        FacesMessage msg = new FacesMessage("Sucessful", "Photo Sucessfully Deleted");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    //used to populate the selection list
    public ArrayList<SelectItem> retrievePhotoList() {
        ArrayList<SelectItem> resultList = new ArrayList<SelectItem>();
        resultList = portalManagementSB.getAllPhoto(retrieveFromSessionOutletID().toString(), "gallery");
        return resultList;
    }

//    private PhotoUploadSB lookupPortalManagementSB() {
//        try {
//            javax.naming.Context c = new InitialContext();
//            return (PhotoUploadSB) c.lookup("java:global/Foodsage/Foodsage-ejb/PortalManagementSB!session.TX.PortalManagementSB");
//        } catch (NamingException ne) {
//            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
//            throw new RuntimeException(ne);
//        }
//    }

    //PHOTO UPLOAD METHODS USED BY STAKEHOLDER
    //===========================================================================================================================
    public void handleAdvertisementPhotoUpload(FileUploadEvent event) {

        ///////////////////////////////////////////////////////////////////////////////////////
        //Construct File Path and Set Type Here
        ///////////////////////////////////////////////////////////////////////////////////////
        String type = "gallery"; //declare type here
        String filePath = "stakeholderUploads/" + retrieveFromSessionStakeholderName() + "/Advertisement/";
        String fileName = event.getFile().getFileName().replace(" ","");
        System.out.println(filePath);
        photoFilePath = "../" + filePath + fileName;
        System.out.println(photoFilePath);
        ///////////////////////////////////////////////////////////////////////////////////////

        boolean success;


        try {
            InputStream inputStream = event.getFile().getInputstream(); //get the file name.
            success = portalManagementSB.insertPhoto(inputStream, fileName, filePath, retrieveFromSessionStakeholderName(), type);
            if (success) {
                FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                //  init();
            } else {
                FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR, "The files were not uploaded!", "");
                FacesContext.getCurrentInstance().addMessage(null, error);
            }

        } catch (IOException e) {
            e.printStackTrace();

            FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR, "The files were not uploaded!", "");
            FacesContext.getCurrentInstance().addMessage(null, error);
        }
    }
    //===========================================================================================================================

    //PHOTO UPLOAD METHODS USED BY OUTLET MANAGER 
    //===========================================================================================================================
    //handles photo upload
    //full file path must be constructed here before passing it onto the session bean
    public void handleDishPhotoUpload(FileUploadEvent event) {

        ///////////////////////////////////////////////////////////////////////////////////////
        //Construct File Path and Set Type Here
        ///////////////////////////////////////////////////////////////////////////////////////
        String type = "gallery"; //declare type here
        String filePath = "stakeholderUploads/" + retrieveFromSessionStakeholderName() + "/" + retrieveFromSessionOutletID() + "/Dish/";
        String fileName = event.getFile().getFileName().replace(" ","");
        System.out.println(filePath);
        photoFilePath = "../../" + filePath + fileName;
        System.out.println(photoFilePath);
        ///////////////////////////////////////////////////////////////////////////////////////

        boolean success;


        try {
            InputStream inputStream = event.getFile().getInputstream(); //get the file name.
            success = portalManagementSB.insertPhoto(inputStream, fileName, filePath, retrieveFromSessionOutletID().toString(), type);
            if (success) {
                FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                //  init();
            } else {
                FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR, "The files were not uploaded!", "");
                FacesContext.getCurrentInstance().addMessage(null, error);
            }

        } catch (IOException e) {
            e.printStackTrace();

            FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR, "The files were not uploaded!", "");
            FacesContext.getCurrentInstance().addMessage(null, error);
        }
    }

    //handles photo upload
    //full file path must be constructed here before passing it onto the session bean
    public void handlePhotoUpload(FileUploadEvent event) {

        ///////////////////////////////////////////////////////////////////////////////////////
        //Construct File Path and Set Type Here
        ///////////////////////////////////////////////////////////////////////////////////////
        String type = "gallery"; //declare type here
        String filePath = "stakeholderUploads/" + retrieveFromSessionOutletOwner() + "/" + retrieveFromSessionOutletID() + "/";
        ///////////////////////////////////////////////////////////////////////////////////////
        String fileName = event.getFile().getFileName().replace(" ","");
        boolean success;
        photoFilePath = "../../" + filePath + fileName;

        try {
            InputStream inputStream = event.getFile().getInputstream(); //get the file name.
            success = portalManagementSB.insertPhoto(inputStream, fileName, filePath, retrieveFromSessionOutletID().toString(), type);
            if (success) {
                FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                // init();
            } else {
                FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR, "The files were not uploaded!", "");
                FacesContext.getCurrentInstance().addMessage(null, error);
            }

        } catch (IOException e) {
            e.printStackTrace();

            FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR, "The files were not uploaded!", "");
            FacesContext.getCurrentInstance().addMessage(null, error);
        }
    }
    //===========================================================================================================================

    //Getters and Setters//
    public String getFolderToUpload() {
        return folderToUpload;
    }

    public void setFolderToUpload(String folderToUpload) {
        this.folderToUpload = folderToUpload;
    }

    public ArrayList<String> getPhotoIDCollection() {
        return photoIDCollection;
    }

    public void setPhotoIDCollection(ArrayList<String> photoIDCollection) {
        this.photoIDCollection = photoIDCollection;
    }

    public PhotoUploadSB getPortalManagementSB() {
        return portalManagementSB;
    }

    public void setPortalManagementSB(PhotoUploadSB portalManagementSB) {
        this.portalManagementSB = portalManagementSB;
    }

    public String getPhotoURLToShow() {
        return photoURLToShow;
    }

    public void setPhotoURLToShow(String photoURLToShow) {
        this.photoURLToShow = photoURLToShow;
    }

    /*  public String retrieveFromSessionStakeholderName() {
    return stakeholderName;
    }
    
    public void setStakeholderName(String stakeholderName) {
    this.stakeholderName = stakeholderName;
    }
     */
    public String getEffect() {
        return effect;
    }

    public void setEffect(String effect) {
        this.effect = effect;
    }

    public List<String> getImages() {
        return images;
    }

    public void setImages(List<String> images) {
        this.images = images;
    }

    public String getAltDesc() {
        return altDesc;
    }

    public void setAltDesc(String altDesc) {
        this.altDesc = altDesc;
    }

    public String getSinglePhotoStr() {
        return singlePhotoStr;
    }

    public void setSinglePhotoStr(String singlePhotoStr) {
        this.singlePhotoStr = singlePhotoStr;
    }

    /**
     * @return the dishFilePath
     */
    public String getPhotoFilePath() {
        return photoFilePath;
    }


    
     //PHOTO UPLOAD METHODS USED BY STAKEHOLDER
    //===========================================================================================================================
    public void handleEventPhotoUpload(FileUploadEvent event) {

        ///////////////////////////////////////////////////////////////////////////////////////
        //Construct File Path and Set Type Here
        ///////////////////////////////////////////////////////////////////////////////////////
         System.out.println("++++uploadstarthere+++++");
        String type = "gallery"; //declare type here
        String filePath = "stakeholderUploads/" + retrieveFromSessionStakeholderName() + "/Event/";
        String fileName = event.getFile().getFileName().replace(" ","");
        System.out.println(filePath);
        photoFilePath = "../"+ filePath + fileName;
        System.out.println(photoFilePath);
        ///////////////////////////////////////////////////////////////////////////////////////

        boolean success;


        try {
            InputStream inputStream = event.getFile().getInputstream(); //get the file name.
            success = portalManagementSB.insertPhoto(inputStream, fileName, filePath, retrieveFromSessionStakeholderName(), type);
            if (success) {
                FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                //  init();
            } else {
                FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR, "The files were not uploaded!", "");
                FacesContext.getCurrentInstance().addMessage(null, error);
            }

        } catch (IOException e) {
            e.printStackTrace();

            FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR, "The files were not uploaded!", "");
            FacesContext.getCurrentInstance().addMessage(null, error);
        }
    }
     //PHOTO UPLOAD METHODS USED BY STAKEHOLDER
    //===========================================================================================================================
    public void handleVenuePhotoUpload(FileUploadEvent event) {

        ///////////////////////////////////////////////////////////////////////////////////////
        //Construct File Path and Set Type Here
        ///////////////////////////////////////////////////////////////////////////////////////
         System.out.println("++++uploadstarthere+++++");
        String type = "gallery"; //declare type here
        String filePath = "stakeholderUploads/" + "Tcube"+ "/Event/";
        String fileName = event.getFile().getFileName().replace(" ","");
        System.out.println(filePath);
        photoFilePath = "../"+ filePath + fileName;
        System.out.println(photoFilePath);
        ///////////////////////////////////////////////////////////////////////////////////////

        boolean success;


        try {
            InputStream inputStream = event.getFile().getInputstream(); //get the file name.
            success = portalManagementSB.insertPhoto(inputStream, fileName, filePath, retrieveFromSessionStakeholderName(), type);
            if (success) {
                FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                //  init();
            } else {
                FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR, "The files were not uploaded!", "");
                FacesContext.getCurrentInstance().addMessage(null, error);
            }

        } catch (IOException e) {
            e.printStackTrace();

            FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR, "The files were not uploaded!", "");
            FacesContext.getCurrentInstance().addMessage(null, error);
        }
    }
    
    
    
    public String retrieveFromSessionStakeholderName(){
        String name = "";
        try{
            name = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("stakeholderName").toString();
        }catch(NullPointerException e){
            return null;
        }
        return name.replace(" ","");
    }
    
    //Randall: Added this method to pull out the outlet ID from session
    public Long retrieveFromSessionOutletID() {
        return (Long) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("outletId");
    }

    public String retrieveFromSessionOutletOwner() {
        return FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("outletOwner").toString();
    }
}
